#include "stdafx.h"
#include "PrinterTypeList.h"
#include "xml.h"

CPrinterTypeList::CPrinterTypeList(void)
{
	m_strServerName = _T("gutenprint");
}

CPrinterTypeList::~CPrinterTypeList(void)
{
	m_PrinterList.RemoveAll();
}

BOOL CPrinterTypeList::Init(const CString& strFileName)
{
	CXMLElement* pXml = CXMLElement::FromFile(strFileName);
	if (!pXml)
	{
		TRACE(_T("XML read failed.\n"));
		return FALSE;
	}

	if (!pXml->IsNamed(m_strServerName))
	{
		TRACE(_T("XML not for printer xml files for %s.\n"), m_strServerName);
		return FALSE;
	}
	CXMLElement* pPrintXml = pXml->GetFirstElement();
	if (!pPrintXml || !pPrintXml->IsNamed(_T("printdef")))
	{
		TRACE(_T("XML not for printer xml files, no printdef Node\n"));
		return FALSE;
	}

	for (POSITION pos = pPrintXml->GetElementIterator(); pos; )
	{
		CXMLElement* pSub = pPrintXml->GetNextElement(pos);
		if (!pSub->IsNamed(_T("family")))
			continue;
		LoadPrinterFamily(pSub);
	}
	delete pXml;

	return TRUE;
}

BOOL CPrinterTypeList::LoadPrinterFamily(CXMLElement* pXml)
{
	CString family = pXml->GetAttributeValue(_T("name"));
	CString temp;
	for (POSITION pos = pXml->GetElementIterator(); pos; )
	{
		CXMLElement* pSub = pXml->GetNextElement(pos);
		if (!pSub->IsNamed(_T("printer")))
			continue;
		PRINTER_TYPE item;
		PRINTER_TYPE* pItem = &item;//new PRINTER_TYPE;
		pItem->family = family;
		pItem->name = pSub->GetAttributeValue(_T("name"));
		pItem->driver = pSub->GetAttributeValue(_T("driver"));
		pItem->manufacturer = pSub->GetAttributeValue(_T("manufacturer"));
		for (POSITION subpos = pSub->GetElementIterator(); subpos;)
		{
			CXMLElement* pSub2 = pSub->GetNextElement(subpos);
			temp = pSub2->GetValue();
			if (pSub2->GetAttributeValue(_T("name")) == _T("Gamma"))
				pItem->Gamma = _tstof(temp);
			if (pSub2->GetAttributeValue(_T("name")) == _T("Density"))
				pItem->Density = _tstof(temp);
			if (pSub2->GetAttributeValue(_T("name")) == _T("cmyk"))
				pItem->CmykProfile = temp;
		}
		m_PrinterList.Add(item);
	}
	return TRUE;
};

BOOL CPrinterTypeList::FillComboBox(CComboBox* pComboBox)
{
	int nCount = m_PrinterList.GetSize();
	for (int i = 0; i < nCount; i++)
	{
		pComboBox->AddString(m_PrinterList[i].name);
		pComboBox->SetItemDataPtr(i, &m_PrinterList[i]);
	}
	return TRUE;
}